<template>
	<view class="map-container">
		<!-- 地图组件 -->
		<map id="map" class="map" :latitude="userLocation.latitude" :longitude="userLocation.longitude"
			:markers="markers" :polyline="polyline" :circles="circles" @show-location="true">
		</map>

		<!-- 导航面板 -->
		<!-- <view class="nav-panel" v-if="isNavigating">
			<view class="nav-info">
				<view class="distance">{{ remainingDistance }}</view>
				<view class="time">{{ remainingTime }}</view>
			</view>
			<view class="next-turn">
				<text>下一个路口</text>
				<text class="turn-info">{{ nextTurnInfo }}</text>
			</view>
		</view> -->

		<!-- 控制面板 -->
		<!-- <view class="control-panel" v-if="!isNavigating">
			<button @tap="addWaypoint">添加途经点</button>
			<button @tap="calculateRoute" :disabled="markers.length < 2">计算路线</button>
			<button @tap="clearAll">清空路线</button>
		</view> -->

		<!-- 导航控制面板 -->
		<!-- <view class="nav-control-panel" v-if="isNavigating">
			<button @tap="stopNavigation">结束导航</button>
			<button @tap="recenterMap">重新定位</button>
		</view> -->

		<!-- 开始导航按钮 -->
		<!-- <view class="start-nav-button" v-if="polyline.length > 0 && !isNavigating">
			<button @tap="startNavigation">开始导航</button>
		</view> -->



	</view>
</template>

<script>
	// 引入腾讯地图SDK
	import QQMapWX from '@/utils/qqmap-wx-jssdk.js';
	import configdata from '@/common/config.js'
	export default {
		data() {
			return {
				// 地图中心点
				center: {
					latitude: 34.673158,
					longitude: 112.436811
				},
				// 标记点数组
				markers: [],
				// 路线数据
				polyline: [],
				// 圆形区域（用于显示当前位置精度）
				circles: [],
				// 途经点集合
				waypoints: [],
				// 腾讯地图实例
				qqmapsdk: null,
				// 地图上下文
				mapContext: null,
				// 是否正在导航
				isNavigating: false,
				// 用户当前位置
				userLocation: null,
				// 位置更新定时器
				locationTimer: null,
				// 当前路线点索引
				currentPointIndex: 0,
				// 剩余距离
				remainingDistance: '0米',
				// 剩余时间
				remainingTime: '0分钟',
				// 下一个转向信息
				nextTurnInfo: '直行',
				// 完整路线点数组
				routePoints: [],
				// 路线总距离
				totalDistance: 0,
				// 路线总时间
				totalTime: 0,





			};
		},

		onReady() {
			// 获取用户当前位置
			this.getUserLocation();
			this.getList()
		},

		onUnload() {
			// 页面卸载时清理定时器
			if (this.locationTimer) {
				clearInterval(this.locationTimer);
			}
		},


		methods: {
			// 初始化地图
			initMap() {
				// 创建地图上下文
				this.mapContext = uni.createMapContext('map', this);

				// 初始化腾讯地图SDK
				this.qqmapsdk = new QQMapWX({
					key: configdata.MapKey // 替换为你的腾讯地图Key
				});

				// 更新用户位置标记
				this.updateUserLocationMarker();
			},



			getList() {
				try {
					const userId = uni.getStorageSync('userId');
					console.log('同步获取数据:', userId);
					this.$Request.getT('/app/riderLine/queryRiderLine', {
						userId: userId
					}).then(res => {
						if (res.code == 0 && res.data) {
							this.markers.push({
								id: 0,
								latitude: res.data.startPointLat,
								longitude: res.data.startPointLng,
								title: `起始点`,
								iconPath: '../../static/image/start.png',
								width: 50,
								height: 50,
								callout: {
									content: '起始点',
									color: '#ffffff',
									fontSize: 12,
									borderRadius: 4,
									bgColor: '#01b001',
									padding: 4,
									display: 'ALWAYS'
								}
							}, {
								id: res.data.wayPoints.length + 1,
								latitude: res.data.endPointLat,
								longitude: res.data.endPointLng,
								title: `结束点`,
								iconPath: '../../static/image/end.png',
								width: 40,
								height: 40,
								callout: {
									content: '结束点',
									color: '#ffffff',
									fontSize: 12,
									borderRadius: 4,
									bgColor: '#01b001',
									padding: 4,
									display: 'ALWAYS'
								}
							});


						}
					});
				} catch (err) {
					console.error('同步获取失败:', err);
				}

			},








			// 获取用户当前位置
			getUserLocation() {
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						this.userLocation = {
							latitude: res.latitude,
							longitude: res.longitude
						};
						this.initMap()
						this.$nextTick(() => {
							this.calculateRoute()
						})
					},
					fail: (err) => {
						console.error('获取位置失败:', err);
						uni.showToast({
							title: '获取位置失败',
							icon: 'none'
						});
					}
				});
			},

			// 更新用户位置标记
			updateUserLocationMarker() {
				if (!this.userLocation) return;

				const userMarker = {
					id: 999,
					latitude: this.userLocation.latitude,
					longitude: this.userLocation.longitude,
					title: '我的位置',
					// iconPath: '../../static/image/user-location.png',
					width: 30,
					height: 40,
					callout: {
						content: '当前位置',
						color: '#ffffff',
						fontSize: 12,
						borderRadius: 4,
						bgColor: '#F24E4E',
						padding: 4,
						display: 'ALWAYS'
					}
				};

				// 查找是否已存在用户位置标记
				const userMarkerIndex = this.markers.findIndex(marker => marker.id === 999);
				if (userMarkerIndex > -1) {
					// 更新现有标记
					this.markers.splice(userMarkerIndex, 1, userMarker);
				} else {
					// 添加新标记
					this.markers.push(userMarker);
				}

				// 添加位置精度圆圈
				this.circles = [{
					latitude: this.userLocation.latitude,
					longitude: this.userLocation.longitude,
					radius: 15,
					fillColor: '#367EEF20',
					color: '#367EEF40',
					strokeWidth: 1
				}];
			},




			// 计算路线
			calculateRoute() {

				const markerList = this.markers.filter(it => it.id != 999)
				// 转换格式：{latitude, longitude} -> "lat,lng"
				const waypointsStr = markerList.map(point =>
					`${point.latitude},${point.longitude}`
				).join(';');

				// 清空旧路线
				this.polyline = [];

				// 调用路线规划API
				this.$nextTick(() => {
					console.log(markerList);
					this.qqmapsdk.direction({
						mode: 'driving',
						from: `${markerList[0].latitude},${markerList[0].longitude}`,
						to: `${markerList[markerList.length-1].latitude},${markerList[markerList.length-1].longitude}`,
						waypoints: waypointsStr,
						success: this.handleRouteSuccess,
						fail: (err) => {
							console.error('路线规划失败:', err);
							uni.showToast({
								title: '路线规划失败',
								icon: 'none'
							});
						}
					});
				})

			},

			// 路线规划成功回调
			handleRouteSuccess(res) {
				if (!res.result || !res.result.routes || res.result.routes.length === 0) {
					uni.showToast({
						title: '未找到可行路线',
						icon: 'none'
					});
					return;
				}

				const route = res.result.routes[0];
				const coors = route.polyline;
				const kr = 1000000; // 压缩系数

				// 坐标解压算法
				for (let i = 2; i < coors.length; i++) {
					coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
				}

				// 生成路径点数组
				const points = [];
				for (let i = 0; i < coors.length; i += 2) {
					points.push({
						latitude: coors[i],
						longitude: coors[i + 1]
					});
				}

				// 保存路线点用于导航
				this.routePoints = points;

				// 更新路线数据
				this.polyline = [{
					points: points,
					color: '#367EEF',
					width: 6,
					borderWidth: 2,
					borderColor: '#5B98FD',
					arrowLine: true
				}];

				// 保存路线信息
				this.totalDistance = route.distance || 0;
				this.totalTime = route.duration || 0;

				// 自动调整视野
				this.mapContext.includePoints({
					points: points,
					padding: [40, 40, 40, 40]
				});

				// 更新距离和时间显示
				this.updateRouteInfo();
			},

			// 更新路线信息显示
			updateRouteInfo() {
				// 格式化距离
				if (this.totalDistance < 1000) {
					this.remainingDistance = `${this.totalDistance}米`;
				} else {
					this.remainingDistance = `${(this.totalDistance / 1000).toFixed(1)}公里`;
				}

				// 格式化时间
				if (this.totalTime < 60) {
					this.remainingTime = `${this.totalTime}分钟`;
				} else {
					const hours = Math.floor(this.totalTime / 60);
					const minutes = this.totalTime % 60;
					this.remainingTime = `${hours}小时${minutes}分钟`;
				}
			},

			// 开始导航
			startNavigation() {
				if (this.routePoints.length === 0) {
					uni.showToast({
						title: '请先计算路线',
						icon: 'none'
					});
					return;
				}

				this.isNavigating = true;
				this.currentPointIndex = 0;

				// 开始位置更新
				this.startLocationTracking();

				// 设置地图跟随用户位置
				this.recenterMap();

				uni.showToast({
					title: '开始导航',
					icon: 'success'
				});
			},

			// 开始位置跟踪
			startLocationTracking() {
				// 清除之前的定时器
				if (this.locationTimer) {
					clearInterval(this.locationTimer);
				}

				// 每3秒更新一次位置
				this.locationTimer = setInterval(() => {
					this.updateUserLocation();
				}, 3000);
			},

			// 更新用户位置
			updateUserLocation() {
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						this.userLocation = {
							latitude: res.latitude,
							longitude: res.longitude
						};

						// 更新用户位置标记
						this.updateUserLocationMarker();

						// 检查是否接近路线终点
						this.checkArrival();

						// 更新导航信息
						this.updateNavigationInfo();
					},
					fail: (err) => {
						console.error('更新位置失败:', err);
					}
				});
			},

			// 检查是否到达终点
			checkArrival() {
				if (!this.userLocation || this.routePoints.length === 0) return;

				const endPoint = this.routePoints[this.routePoints.length - 1];
				const distance = this.calculateDistance(
					this.userLocation.latitude,
					this.userLocation.longitude,
					endPoint.latitude,
					endPoint.longitude
				);

				// 如果距离终点小于50米，认为已到达
				if (distance < 50) {
					this.stopNavigation();
					uni.showModal({
						title: '导航完成',
						content: '您已到达目的地',
						showCancel: false
					});
				}
			},

			// 更新导航信息
			updateNavigationInfo() {
				if (!this.userLocation || this.routePoints.length === 0) return;

				// 计算剩余距离和时间
				const remainingPoints = this.routePoints.slice(this.currentPointIndex);
				let totalRemainingDistance = 0;

				for (let i = 0; i < remainingPoints.length - 1; i++) {
					totalRemainingDistance += this.calculateDistance(
						remainingPoints[i].latitude,
						remainingPoints[i].longitude,
						remainingPoints[i + 1].latitude,
						remainingPoints[i + 1].longitude
					);
				}

				// 更新显示信息
				if (totalRemainingDistance < 1000) {
					this.remainingDistance = `${Math.round(totalRemainingDistance)}米`;
				} else {
					this.remainingDistance = `${(totalRemainingDistance / 1000).toFixed(1)}公里`;
				}

				// 估算剩余时间（假设平均速度30km/h）
				const speed = 30; // km/h
				const remainingTimeHours = totalRemainingDistance / 1000 / speed;
				const remainingMinutes = Math.round(remainingTimeHours * 60);
				this.remainingTime = `${remainingMinutes}分钟`;
			},

			// 计算两点间距离（米）
			calculateDistance(lat1, lng1, lat2, lng2) {
				const radLat1 = lat1 * Math.PI / 180.0;
				const radLat2 = lat2 * Math.PI / 180.0;
				const a = radLat1 - radLat2;
				const b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
				let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
					Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
				s = s * 6378.137; // EARTH_RADIUS
				s = Math.round(s * 10000) / 10;
				return s;
			},

			// 重新定位地图中心到用户位置
			recenterMap() {
				if (this.userLocation) {
					this.mapContext.moveToLocation({
						latitude: this.userLocation.latitude,
						longitude: this.userLocation.longitude
					});
				}
			},

			// 停止导航
			stopNavigation() {
				this.isNavigating = false;

				// 清除位置更新定时器
				if (this.locationTimer) {
					clearInterval(this.locationTimer);
					this.locationTimer = null;
				}

				// 移除用户位置标记
				const userMarkerIndex = this.markers.findIndex(marker => marker.id === 999);
				if (userMarkerIndex > -1) {
					this.markers.splice(userMarkerIndex, 1);
				}

				// 清空位置精度圆圈
				this.circles = [];

				uni.showToast({
					title: '导航已结束',
					icon: 'none'
				});
			},

			// 清空所有
			clearAll() {
				this.markers = [this.markers[0]]; // 保留起点
				this.polyline = [];
				this.waypoints = [];
				this.routePoints = [];
				this.isNavigating = false;

				// 清除定时器
				if (this.locationTimer) {
					clearInterval(this.locationTimer);
					this.locationTimer = null;
				}

				// 清空导航相关信息
				this.currentPointIndex = 0;
				this.remainingDistance = '0米';
				this.remainingTime = '0分钟';
				this.nextTurnInfo = '直行';
				this.circles = [];
			}
		}
	};
</script>

<style>
	.map-container {
		position: relative;
		height: 100vh;
	}

	.map {
		width: 100%;
		height: 100vh;
	}

	.control-panel {
		position: absolute;
		top: 20px;
		left: 0;
		right: 0;
		display: flex;
		justify-content: center;
		gap: 15px;
		padding: 10px;
		z-index: 100;
	}

	.nav-panel {
		position: absolute;
		top: 20px;
		left: 20px;
		right: 20px;
		background: rgba(255, 255, 255, 0.9);
		border-radius: 10px;
		padding: 15px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
		z-index: 100;
	}

	.nav-info {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10px;
	}

	.distance {
		font-size: 24px;
		font-weight: bold;
		color: #333;
	}

	.time {
		font-size: 18px;
		color: #666;
		align-self: flex-end;
	}

	.next-turn {
		font-size: 14px;
		color: #999;
	}

	.turn-info {
		color: #367EEF;
		margin-left: 10px;
	}

	.nav-control-panel {
		position: absolute;
		bottom: 100px;
		left: 0;
		right: 0;
		display: flex;
		justify-content: center;
		gap: 15px;
		padding: 10px;
		z-index: 100;
	}

	.start-nav-button {
		position: absolute;
		bottom: 100px;
		left: 0;
		right: 0;
		display: flex;
		justify-content: center;
		z-index: 100;
	}

	button {
		background-color: #367EEF;
		color: white;
		border-radius: 20px;
		padding: 8px 20px;
		font-size: 14px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
		border: none;
	}

	button[disabled] {
		background-color: #cccccc;
		opacity: 0.7;
	}
</style>